package com.yox.rpc.util;

import com.yox.rpc.entity.RpcRequest;
import com.yox.rpc.entity.RpcResponse;
import com.yox.rpc.enumeration.ResponseCode;
import com.yox.rpc.enumeration.RpcError;
import com.yox.rpc.exception.RpcException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 检查响应与请求
 *
 * 利用请求号对服务端返回的响应数据进行校验，保证请求与响应一一对应
 */
public class RpcMessageChecker {

    public static final String INTERFACE_NAME = "interfaceName";
    private static final Logger logger = LoggerFactory.getLogger(RpcMessageChecker.class);

    private RpcMessageChecker(){}

    public static void check(RpcRequest rpcRequest, RpcResponse rpcResponse) {
        // 没有返回响应值
        if (rpcResponse == null) {
            logger.error("没有返回响应值，调用服务失败，serviceName：{}", rpcRequest.getInterfaceName());
            throw new RpcException(RpcError.SERVICE_INVOVATION_FAILURE, INTERFACE_NAME + ":" + rpcRequest.getInterfaceName());
        }

        // 响应与请求号不匹配
        if (!rpcRequest.getRequestID().equals(rpcResponse.getRequestID())) {
            logger.error("响应与请求号不匹配");
            throw new RpcException(RpcError.RESPONSE_NOT_MATCH, INTERFACE_NAME + ":" + rpcRequest.getInterfaceName());
        }

        // 服务调用出错
        if (rpcResponse.getStatusCode() == null || !rpcResponse.getStatusCode().equals(ResponseCode.SUCCESS.getCode())) {
            logger.error("调用服务出错，serviceName:{}, RpcResponse:{}", rpcRequest.getInterfaceName(), rpcResponse);
        }
    }
}
